package com.integrate.rabbitmq.consumer;


import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 消息的标识，false只确认当前一个消息收到，true确认所有consumer获得的消息
 * channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
 * ack返回false，并重新回到队列，api里面解释得很清楚
 * channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
 * 拒绝消息
 * channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
 * 丢弃这条消息
 * channel.basicNack(message.getMessageProperties().getDeliveryTag(), false,false);
 * @author 刘志强
 * @date 2020/11/13 13:45
 */
@Component
@Slf4j
public class RabbitConsumer {

    /**
     * 订阅queue队列 消费消息
     * @param object
     */
    @RabbitListener(queues="queue")
    public void consumerQueue(Channel channel, Object object, Message message) throws IOException {
        log.info("consumerQueue 消费来自queue队列消息，消息内容为" + object);
        // 告诉Rabbit已消费，从队列中删除
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    /**
     * 订阅queue队列 不消费消息，并将消息返回队列
     * @param object
     */
    @RabbitListener(queues="queue")
    public void noConsumerQueue(Channel channel, Object object, Message message) throws IOException {
        log.info("noConsumerQueue 消费来自queue队列消息，消息内容为" + object);
        // 不消费并返回队列
        channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);

    }


    /**
     * 订阅memberQueue队列
     * @param object
     */
    @RabbitListener(queues="memberQueue")
    public void consumerMemberQueue(Channel channel, Object object, Message message) throws IOException {
        log.info("consumerMemberQueue 消费memberQueue队列消息，消息内容为" + object);
        // 告诉Rabbit已消费，从队列中删除
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    /**
     * 订阅死信队列，当延迟队列的消息死亡时。消息会进入死信队列
     * @param channel
     * @param object
     * @param message
     * @throws IOException
     */
    @RabbitListener(queues="deathQueue")
    public void deathQueue(Channel channel, Object object, Message message) throws IOException {
        log.info("deathQueue 消费deathQueue队列消息，消息内容为" + object);
        // 告诉Rabbit已消费，从队列中删除
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}


